package com.maotai.llzhou.thread;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.config.RequestConfig;

import Decoder.BASE64Encoder;
import cn.hellotrue.HelloTrueNJ;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maotai.llzhou.bean.MaotaiString;
import com.maotai.llzhou.bean.MaotaiWebCookie;
import com.maotai.llzhou.service.MaotaiService;
import com.maotai.llzhou.util.HttpClientUtilNew;
import com.maotai.llzhou.util.IPFactory;

public class MaoTaiRegisterThreadNJ extends Thread {

	private MaotaiService maotaiService;

	public MaoTaiRegisterThreadNJ(MaotaiService maotaiService) {
		super();
		this.maotaiService = maotaiService;
	}

	public MaotaiService getMaotaiService() {
		return maotaiService;
	}

	public void setMaotaiService(MaotaiService maotaiService) {
		this.maotaiService = maotaiService;
	}

	@Override
	public void run() {
		MaotaiWebCookie mwc = new MaotaiWebCookie();
		BASE64Encoder encode = new BASE64Encoder();
		HttpClientUtilNew hcu = HttpClientUtilNew.getInstance();
		//获取一个待注册的手机号
		try {
		Map<String, Object> phone = maotaiService.getRegisterPhone();
		if(phone==null) return;
		phone.put("usestatus", "1");
		maotaiService.updateRegisterPhoneStatus(phone);
		String telphone = phone.get("code")+"";
		//调用api获取密码
		HelloTrueNJ ht = new HelloTrueNJ();
		String phoneResult = "";
		String orderId = "";
		String messageResult = "";
		String checkCode = "";
		while(true){
			phoneResult = ht.getPhone(telphone);
			System.out.println(telphone+"--getPhone--"+phoneResult);
			if(phoneResult.contains("稍后再试")){
				Thread.sleep(3000);
			}else if(phoneResult.contains("无法锁定")){
				phone.put("usestatus", "0");
				maotaiService.updateRegisterPhoneStatus(phone);
				return;
			}else{
				JSONObject phoneJ = JSONObject.parseObject(phoneResult);
				if ("error".equals(phoneJ.getString("status"))){
//					phone.put("usestatus", "0");
//					maotaiService.updateRegisterPhoneStatus(phone);
					return;
				}
				// {"status":"success","errorMsg":null,"errorCode":null,"module":{"bizOrderId":"989059","phone":"13405832132"}}
				orderId = phoneJ.getJSONObject("module").getString("bizOrderId");
				break;
			}
		}
		JSONArray jArray = IPFactory.getIpAndPort();
		JSONObject jj = (JSONObject) jArray.get(0);
		String ipAndPort = jj.getString("ip") + ":"
				+ jj.getString("port");
		//先登录
		Map<String, String> maps = new HashMap<String, String>();
		//userCode=nickboowen&userPassword=MTk4NjA2MTg&loginType=name&loginSource=2&loginFlag=1
		maps.put("userCode", telphone);
		maps.put("userPassword", "MTIzNDU2");
		maps.put("loginType", "name");
		maps.put("loginSource", "2");
		maps.put("loginFlag", "1");
		//loginSource=2&loginType=name&userCode=13372007847&userPassword=cTE5ODYwNjE4 手机端
		String referer = "https://www.emaotai.cn/smartsales-b2c-web-pc/login";
		RequestConfig requestConfig = IPFactory.getKdRequestConfig(ipAndPort);
		try {
			mwc = hcu.sendHttpPostProxy(MaotaiString.LOGIN_URL_NEW,
					mwc, maps, requestConfig,referer);
		} catch (Exception e) {
			e.printStackTrace();
			phone.put("usestatus", "0");
			maotaiService.updateRegisterPhoneStatus(phone);
			return;
		}
		if(mwc.getContent().contains("不存在")){
			
		}else{
			System.out.println(telphone+"----"+mwc.getContent());
			//执行修改密码操作
			return;
		}
		
		//发送验证码到手机
		String send_url = MaotaiString.SEND_MOBILE_URL.replace("xxx", telphone);
		
		RequestConfig config = IPFactory.getKdRequestConfig(ipAndPort);
		mwc = hcu.sendHttpGetProxy(send_url, mwc, config, MaotaiString.REGISTER_REFERER_URL);
		//{"data":"发送成功","resultCode":0,"resultMsg":"success"}
		System.out.println(telphone+"----"+mwc.getContent());
		
		//接收验证码
		//TODO
		String pwd = encode.encode(("a"+telphone).getBytes());
		pwd = pwd.replace("=", "");
		while(true){
			messageResult = ht.getMessage(orderId);
			System.out.println(telphone+"--getMessage--"+messageResult);
			if(phoneResult.contains("稍后再试")){
				Thread.sleep(3000);
			}else if(phoneResult.contains("无法锁定")){
				phone.put("usestatus", "0");
				maotaiService.updateRegisterPhoneStatus(phone);
				return;
			}else{
				JSONObject messageJ = JSONObject.parseObject(messageResult);
				// {"status":"success","errorMsg":null,"errorCode":null,"module":{"text":null,"checkCode":"345345"}}
				
				checkCode = messageJ.getJSONObject("module").getString("checkCode");
				System.out.println(telphone+"--获取到的验证码信息为：" + checkCode);
				break;
			}
		}
//		String regEx="[^0-9]";   
//		Pattern p = Pattern.compile(regEx);   
//		String telCode = p.matcher(message).replaceAll("").trim().substring(0,6);
//		System.out.println("截取后的验证码信息为：" + telCode);
			Map<String, String> registerMap = new HashMap<String, String>();
			registerMap.put("userName", telphone);
			registerMap.put("password", pwd);
			registerMap.put("mobile", telphone);
			registerMap.put("verifyCode", checkCode);
			registerMap.put("confimpwd", pwd);
			registerMap.put("appCode", "newrretail");
			registerMap.put("channel", "B2C");
			mwc = hcu.sendHttpPostProxy(MaotaiString.REGISTER_URL, mwc, registerMap ,config,MaotaiString.REGISTER_REFERER_URL);
			
			System.out.println(mwc.getContent());
			//{"data":null,"resultCode":-1,"resultMsg":"验证码错误"}
			JSONObject jObject = JSONObject.parseObject(mwc.getContent());
			if(jObject!=null && "您的手机已注册".equals(jObject.getString("retmsg"))){
				System.out.println("手机号已注册");
			}else if(jObject!=null && "success".equals(jObject.getString("retmsg"))){
				System.out.println("手机号未注册，等待获取验证码....");
			}else{
				Map<String,String> map = new HashMap<String,String>();
				map.put("code", telphone);
				map.put("pwd", "a"+telphone);
				map.put("phone", telphone);
				maotaiService.insertZhanghaoWeb(map);
				
				Map<String,Object> zhanghao = new HashMap<String,Object>();
				zhanghao.put("code", telphone);
				zhanghao.put("pwd", "a"+telphone);
				zhanghao.put("phone", telphone);
				//注册完了，进行账号信息补全，补全后进行预约
			}
	} catch (Exception e1) {
		e1.printStackTrace();
	}
	}
}
